// 表格唯一标识
const gridManagerName = 'users';

const index = {
	
	/**
	 * 初始化表格
	 */
	initGM: function() {
		new window.GridManager(table, {
			gridManagerName: 'users',
			width: '100%',
			height: '100%',
			ajaxData: 'http://localhost:8080/netdisc/admin/admin/allUser',
			ajaxType: 'POST',
			columnData: [
				{
					key: 'id',
					text: '用户id'
				}, {
					key: 'username',
					text: '用户名',
					// 使用函数返回 dom node
					template: function(title, rowObject) {
						let titleNode = document.createElement('a');
						titleNode.setAttribute('href', 'http://localhost:8080/netdisc/views/view-admin/file-management.html?userId=' + rowObject.id);
						titleNode.setAttribute('title', title);
						titleNode.setAttribute('target', '_blank');
						titleNode.innerText = title;
						titleNode.title = '查看用户文件';
						titleNode.classList.add('plugin-action');
						return titleNode;
					}
				}, {
					key: 'email',
					text: '邮箱'
				}, {
					key: 'character',
					text: '角色'
				}, {
					key: 'rootId',
					text: '根目录id'
				}, {
					key: 'capacity',
					text: '占用容量'
				}, {
					key: 'isDelete',
					text: '是否删除'
				}
			]
		})
		
	}
}

// GridManager 渲染
const table = document.querySelector('#users');
index.initGM(table);

//获取选中的用户
function getCheckedUsers() {
	let checkedData = GridManager.getCheckedData(gridManagerName);
	let userIds = [];
	for(let i = 0; i < checkedData.length; i ++) {
		userIds.push(checkedData[i].id);
	}
	console.log(userIds);
	return JSON.stringify(userIds);
}

function setVIP() {
	let userIds = getCheckedUsers();
	httpPostWithParams("/admin/setAllUserVIP", userIds,handler)
}

function setCommon() {
	let userIds = getCheckedUsers();
	httpPostWithParams("/admin/setAllUserCommon", userIds,handler)
}

function deleteUser() {
	if( ! confirm("确定删除吗？")) {
		return;
	}
	let userIds = getCheckedUsers();
	httpPostWithParams("/admin/setAllUserInvisible", userIds,handler)
}

function undeleteUser() {
	if( ! confirm("确定取消删除吗？")) {
		return;
	}
	let userIds = getCheckedUsers();
	httpPostWithParams("/admin/setAllUserVisible", userIds,handler)
}

function exit() {
	setCookie("userId", "", - 1);
	setCookie("username", "", - 1);
	setCookie("character", "", - 1);
	location.href = "login.html";
}

function setCookie(cname, cvalue, exdays) {
	let d = new Date();
	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
	let expires = "expires=" + d.toUTCString();
	document.cookie = cname + "=" + cvalue + "; " + expires + ";" + "path=/";
}

function handler(resp) {
	console.log(resp);
	let result = JSON.parse(resp);
	alert(result.message);
	GridManager.refreshGrid(gridManagerName);
}